<?php
/**
 * 《物料库存》实现类
 *
 * @author 孙晓晔
 * @version $Id: Amount.class.php 1043 2010-04-01 08:04:38Z sunxy $
 */
require_once(dirname(__FILE__) . '/Bom.class.php');

class Amount extends Bom {
	public $tbl = Constant::tbl_material_amount;

	public $check = array(
		'-' => '请选择',
		'1' => '已盘点',
		'2' => '未盘点',
	);

	public $status = array(
		'-' => '请选择',
		'1' => '正常',
		'2' => '暂停',
		'3' => '停止',
	
		'9' => '其它',
	);

	public $orderby = array(
		'-' => '请选择',
		'name' => '名称',
		'standard' => '规格',
	
		'category' => '大类',
		'subclass' => '小类',

		
		'amount' => '数量',
		'place' => '仓库',
		'1' => '创建时间',
		'2' => '更新时间',
	);

	public $groupby = array(
		'-' => '请选择',
		'emp' => '负责人',
		'place' => '仓库',
		'category' => '大类',
		'type' => '小类',
		'status' => '状态',
	
		'2' => '日期',
		'3' => '月份',
	);

	function __construct() {
		$request['update'] = '$Date: 2009/02/16 07:36:07 $';
		$request['revision'] = '$Revision: 1.1 $';

		parent::__construct($request);
	}

	function pretreat($controller) {
		parent::pretreat($controller);
	}
	
	function tab($controller, $request) {		
		$data = array(
			'物料库存' => array('cc'=>'material.php?do=Amount.find', 'js'=>'1'),	
			// '用料申请' => array('cc'=>'material.php?do=Used.find', 'js'=>''),
			// '用料明细' => array('cc'=>'material.php?do=RecordOut.find', 'js'=>''),
		
			'采购单' => array('cc'=>'material.php?do=PurchaseCk.find', 'js'=>'1'),
			'采购明细' => array('cc'=>'material.php?do=RecordInCk.find', 'js'=>''),
				
			'进货单' => array('cc'=>'material.php?do=Receive.find', 'js'=>''),
			'入库明细' => array('cc'=>'material.php?do=In.find', 'js'=>'1'),
			
			'退货单' => array('cc'=>'material.php?do=Returned.find', 'js'=>''),
			'退货明细' => array('cc'=>'material.php?do=ReturnedItem.find', 'js'=>''),	
				
			// '出库单' => array('cc'=>'material.php?do=Returned.find', 'js'=>''),
			'出库明细' => array('cc'=>'material.php?do=Out.find', 'js'=>'1'),
		
			'盘点信息' => array('cc'=>'material.php?do=PanDian.find', 'js'=>''),
			
			'物料需求' => array('cc'=>'material.php?do=Bom.find', 'js'=>'1'),
			'材料信息' => array('cc'=>'material.php?do=Material.find', 'js'=>''),
			'产品信息' => array('cc'=>'mold.php?do=Mold.find', 'js'=>'1'),
		
			'统计分析' => array('cc'=>'material.php?do=Amount.tj_tab', 'js'=>''),
		);
		
		$ret = $this->_tab($data);

		$controller->assign_by_ref('result', $ret);

		$controller->display($request, 'tab');
		return true;
	}
	
	function tj_tab($controller, $request) {		
		$data = array(
			'物料库存' => array('cc'=>'material.php?do=Amount.group', 'js'=>''),		
			// '用料申请' => array('cc'=>'material.php?do=Used.group', 'js'=>''),
			// '用料明细' => array('cc'=>'material.php?do=RecordOut.group', 'js'=>''),
			'出库明细' => array('cc'=>'material.php?do=Out.group', 'js'=>''),			
		);
		
		$ret = $this->_tab($data);

		$controller->assign_by_ref('result', $ret);

		$controller->display($request, 'tj_tab');
		return true;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function find($controller, $request) {
		$this->pretreat($controller);
		
		$emp = array(
			// '-' => '请选择',
			'emp' => '负责人',
			'oper' => '录入员',
		);
		
		$controller->assign_by_ref('emp_option', $emp);

		$controller->display($request, 'material/amount/find');
		return true;
	}

	function _orderby_x($controller, $row, $px) {
		$orderby = $this->orderby['1'];
		$row['orderby_x'] = $row['createtime'];

		if (empty($px) || $px == '-' || $px == '1') {
			$controller->assign('orderby', $orderby);

			return $row;
		}

		if ($px == '2') {
			$orderby = $this->orderby[$px];
			$row['orderby_x'] = $row['modifytime'];
		}

		if ($px == 'category') {
			$orderby = $this->orderby[$px];
			$row['orderby_x'] = $row['category'];
		}

		if ($px == 'subclass') {
			$orderby = $this->orderby[$px];
			$row['orderby_x'] = $row['subclass'];
		}

		$controller->assign('orderby', $orderby);

		return $row;
	}

	function _where($request) {
		$material_s = $this->_input($request['material_s']);

		$category_s = $request['category_s'];
		$subclass_s = $request['subclass_s'];

		$name_s = addslashes(trim($request['name_s']));
		$standard_s = addslashes(trim($request['standard_s']));
		
		$place_s = $request['place_s'];

		$where = " WHERE 1=1";

		if (!empty($material_s)) {
			$where .= " AND material = '" . $material_s . "'";
		}

		if (!empty($category_s) && $category_s <> '-') {
			$where .= " AND category = '" . $category_s . "'";
		}

		if (!empty($subclass_s) && $subclass_s <> '-') {
			$where .= " AND subclass = '" . $subclass_s . "'";
		}

		if (!empty($name_s)) {
			$where .= " AND (name LIKE '%" . $name_s . "%' OR content LIKE '%" . $name_s . "%')";
		}
		
		if (!empty($standard_s)) {
			$where .= " AND standard LIKE '%" . $standard_s . "%'";
		}

		if (!empty($place_s) && $place_s <> '-') {
			$where .= " AND place = '" . $place_s . "'";
		}

		$where .= $this->_where_default($request);
		$where = $this->_where_aa($where);

		return $where;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function findPost($controller, $request) {
		$this->pretreat($controller);

		$this->findPara($controller, $request);

		$db = newdb($this->dsn_r);
		$fmt = "SELECT * FROM %s a %s %s";
		$where = $this->_where($request);
		$orderby = $this->_orderby();		
		$sql = sprintf($fmt, $this->tbl, $where, $orderby);
		debug($sql);

		$pager_option = array (
            'db' => $db,
            'sql' => $sql,
            'PageSize' => $this->pagesize,
            'CurrentPageID' => $request['p'],
            'numItems' => $request['n']
		);

		$pager = @new Pager($pager_option);
		$data = $pager->getPageData();

		if ($pager->number > 0) {
			$count = 0;
			$from = $pager->from;
			while ($count < $pager->number) {
				$row = $data[$count];
				$row = $this->_view(null, $row);

				$row = $this->_orderby_x($controller, $row, $this->orderby_s);

				$data[$count] = $row;
				$count++;
			}
			$controller->assign_by_ref('result', $data);
			$controller->assign_by_ref('pager', $pager);
		}

		$controller->display($request, 'material/amount/list');
		return true;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function xls($controller, $request) {
		$this->pretreat($controller);
		
		$this->findPara($controller, $request);

		$request['tpl'] = "xls";

		$db = newdb($this->dsn_r);
		$fmt = "SELECT * FROM %s a %s %s";
		$where = $this->_where($request);
		$orderby = $this->_orderby();		
		$sql = sprintf($fmt, $this->tbl, $where, $orderby);
		debug($sql);

		$result = $db->query($sql);
		$data = array();
		while ($row = $db->fetch_array($result)) {
			$row = $this->_view(null, $row);
			
			$row = $this->_orderby_x($controller, $row, $this->orderby_s);

			$data[] = $row;
		}
		$controller->assign_by_ref('result', $data);
		
		$filename = sprintf("%s.xls", date("YmdHis"));
		header('Content-Disposition:application/vnd.ms-excel; filename=' . $filename);

		$controller->display($request, 'material/amount/list');
		return true;
	}
	
	function add($controller, $request) {
		$this->pretreat($controller);
	
		// $controller->assign('t1', strtotime('2 day'));
	
		$controller->display($request, 'material/amount/add');
		return true;
	}
	
	function addPost($controller, $request) {
		$this->pretreat($controller);
	
		$date = $request['date'];
		$mold = $this->_input($request['mold']);
		$material = $this->_input($request['material']);
	
		$type = $request['type'];
		$amount = $request['amount'];
	
		$name = addslashes($request['name']);
		$standard = addslashes($request['standard']);
		$price2 = $request['price2'];
		$unit2 = $request['unit2'];
	
		$density = $request['density'];
	
		if ($type == 1) {
				
			$unit = $unit2;
			$price = $price2;
			$amount2 = $amount;
		} elseif ($type == 2) {
			$v = $this->_v1($standard);
			if (!empty($density) && $density > 0) {
				$n = $v * $density;
			} else {
				$n = $v;
			}
				
			$unit = $request['unit'];
			$price = $n * $price2;
				
			$amount2 = $n * $amount;
		} elseif ($type == 3) {
			$v = $this->_v2($standard);
			if (!empty($density) && $density > 0) {
				$n = $v * $density;
			} else {
				$n = $v;
			}
	
			$unit = $request['unit'];
			$price = $n * $price2;
				
			$amount2 = $n * $amount;
		} elseif ($type == 9) {
			$unit = $request['unit'];
			$price = $price2;
			$amount = $request['amount'];
			$amount2 = $amount;
		} else {
			$unit = $unit2;
			$price = $price2;
			$amount2 = $amount;
		}
		
		$place = $request['place'];
	
		$content = addslashes($request['content']);
	
		$emp = $this->_input($request['emp']);
		$office = $this->_office($emp);
		$dept = $this->_emp_dept($emp);
	
		$db = newdb($this->dsn_w);
		$fmt = "INSERT INTO %s(material, place, name, standard, amount, unit, price, content, emp, oper";
		$fmt .= ", createtime, modifytime) VALUES('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', NOW(), NOW())";
		$sql = sprintf($fmt, $this->tbl, $material, $place, $name, $standard, $amount, $unit, $price, $content, $emp, $_SESSION['id']);
		debug($sql);
		$db->query($sql);
	
		$request['id_s'] = $db->insert_id();
	
		$controller->assign('baseLink', $this->doGet($request, 'findPost'));
	
		$this->findPost($controller, $request);
		return true;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function edit($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];
		$row = $this->_view($id);

		$controller->assign_by_ref('result', $row);

		$controller->display($request, 'material/amount/edit');
		return true;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function editPost($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];
		clean($this->tbl . "_id_" . $id);

		$name = $request['name'];
		$standard = $request['standard'];
		$unit = $request['unit'];
		$price = $request['price'];
		$amount = $request['amount'];

		$place = $request['place'];

		// $content = sprintf("%s\n%s 修改", addslashes($request['content']), Name::emp($_SESSION['id']));
		$content = addslashes($request['content']);
		
		$status = $request['status'];
		
		$emp = $this->_input($request['emp']);
		$office = $this->_office($emp);
		$dept = $this->_emp_dept($emp);
		
		$db = newdb($this->dsn);
		$fmt = "UPDATE %s SET name = '%s', standard = '%s', unit = '%s', price = '%s', amount = '%s', place = '%s', content = '%s', emp = '%s', status = '%s', modifytime = now() WHERE id = '%s'";
		$sql = sprintf($fmt, $this->tbl, $name, $standard, $unit, $price, $amount, $place, $content, $emp, $status, $id);
		// debug($sql);
		$db->query($sql);
		if ($db->error()) {
			$controller->assign("msg", "修改失败，请联系管理员" . $db->error());
			$controller->display($request, 'info');
			return true;
		}
			
		$controller->assign('baseLink', $this->doGet($request, 'findPost'));

		$this->findPost($controller, $request);
		return true;
	}
	
	function exchange($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];
		$row = $this->_view($id);

		$controller->assign_by_ref('result', $row);

		$controller->display($request, 'material/amount/exchange');
		return true;
	}
	
	function exchangePost($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];
		clean($this->tbl . "_id_" . $id);
		
		$row = $this->_view($id);

		$a_amount = $request['a_amount'];
		
		$place = $request['place'];
		
		$name = $request['name'];
		$standard = $request['standard'];
		$unit = $request['unit'];
		$price = $request['price'];
		$amount = $request['amount'];

		$content = addslashes($request['content']);
		
		$db = newdb($this->dsn);
		$fmt = "UPDATE %s SET amount = amount - %s, modifytime = now() WHERE id = '%s'";
		$sql = sprintf($fmt, $this->tbl, $a_amount, $id);
		// debug($sql);
		$db->query($sql);
		if ($db->error()) {
			$controller->assign("msg", "修改失败，请联系管理员" . $db->error());
			$controller->display($request, 'info');
			return true;
		}
		
		$data['name'] = $name;
		$data['standard'] = $standard;
		$data['unit'] = $unit;
		$data['price'] = $price;
		$data['material'] = $row['material'];
		
		$this->_in_update($data, $amount, $place);		
		
		$emp = $_SESSION['id'];
		
		require_once(dirname(__FILE__) . '/Out.class.php');
		$out = new Out();
		$out->_insert($row, $a_amount, date("Y-m-d"));
		
		require_once(dirname(__FILE__) . '/In.class.php');
		$in = new In();
		$in->_insert($data, $amount, $emp, date("Y-m-d"));
				
		$controller->assign('baseLink', $this->doGet($request, 'findPost'));

		$this->findPost($controller, $request);
		return true;
	}

	function cart($controller, $request) {
		$this->pretreat($controller);

		$cart = $request['cart'];
		// echo $cart;
		$a = json_decode($cart);
		// print_r($a);

		$data = array();
		while (list($k, $v) = each($a)) {
			$row = $this->id($this->tbl, $v[0]);
			$m = $this->id(Constant::tbl_material, $row['material']);
			$row['code'] = $m['code'];
			$row['name'] = $m['name'];
			$row['standard'] = $m['standard'];
			$row['unit'] = $m['unit'];

			$data[] = $row;
		}

		$controller->assign_by_ref('result', $data);

		$controller->display($request, 'material/amount/cart');
		return true;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function clean($controller, $request) {
		$cart = $_SESSION['cart'];

		$id = $request['material'];
		$data = array();
		while (list($k, $v) = each($cart)) {
			if ($k == $id) {
				continue;
			}

			$data[$k] = $k;
		}

		$_SESSION['cart'] = $data;

		$this->add($controller, $request);
		return true;
	}

	function view($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];
		$row = $this->_view($id);

		$controller->assign_by_ref('result', $row);

		require_once 'Material.class.php';
		$material = new Material();
		$controller->assign_by_ref('material', $material->_view($row['material']));

		$controller->display($request, 'material/amount/view');
		return true;
	}
	
	function _view($id = 0, $row = null) {
		if ($row == null) {
			clean($this->tbl . "_id_" . $id);
			$row = $this->id($this->tbl, $id);
		}

		$row = $this->_view_t($row);
		
		return $row;
	}
	
	function delete($controller, $request) {
		$this->pretreat($controller);
	
		$db = newdb($this->dsn_w);
		while (list($k, $id) = each($request)) {
			if (substr($k, 0, 2) <> "c_") {
				continue;
			}
			
			$row = $this->_view($id);
			if (!$this->_is_delete($row)) {
				continue;
			}
	
			$this->_delete3($id);
		}
	
		$controller->assign('baseLink', $this->doGet($request, 'findPost'));
	
		$this->findPost($controller, $request);
		return true;
	}
	
	function _delete3($id) {
		$db = newdb($this->dsn_w);
		if ($this->_is_admin()) {
			$fmt = "DELETE FROM %s WHERE id = '%s'";
		} else {
			$fmt = "UPDATE %s SET visible = 2, modifytime = NOW() WHERE id = '%s'";
		}
	
		$sql = sprintf($fmt, $this->tbl, $id);
		debug($sql);
		$db->query($sql);
	}
	
	function _is_delete($row) {
		if ($this->_is_admin()) {
			return true;
		}
		
		$emp = $_SESSION['id'];
		
		if ($row['emp'] == $emp || $row['oper'] == $emp) {
			return true;
		}

		return false;
	}

	function status($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];
		clean($this->tbl . "_id_" . $id);

		$status = $request['status'];

		$db = newdb($this->dsn_w);
		$fmt = "UPDATE %s SET status = '%s', modifytime = now() WHERE id = '%s'";
		$sql = sprintf($fmt, $this->tbl, $status, $id);
		// debug($sql);
		$db->query($sql);

		$controller->assign('baseLink', $this->doGet($request, 'findPost'));

		$this->findPost($controller, $request);
		return true;
	}

	function sync_category($controller, $request) {
		$db = newdb($this->dsn_w);
		$fmt = "UPDATE %s a, %s b SET a.category = b.category, a.type = b.type WHERE a.material = b.id";
		$sql = sprintf($fmt, $this->tbl, Constant::tbl_material);
		debug($sql);
		$db->query($sql);

		return true;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function record($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];
		$row = $this->_view($id);

		$controller->assign_by_ref('result', $row);

		$controller->display($request, 'material/amount/record');
		return true;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function recordPost($controller, $request) {
		$this->pretreat($controller);

		$id = $request['id'];

		$row = $this->id($this->tbl, $id);

		$used = $this->_input($request['used']);
		$amount = $request['amount'];

		$content = addslashes($request['content']);

		$db = newdb($this->dsn_w);
		$fmt = "INSERT INTO %s(used, place, material, name, standard, unit, amount, content, emp, createtime, modifytime)";
		$fmt .= " VALUES('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', now(), now())";
		$sql = sprintf($fmt, Constant::tbl_wl_record_out, $used, $row['place'], $row['material'], $row['name'], $row['standard'], $row['unit'], $amount, $content, $row['emp']);
		debug($sql);
		$db->query($sql);

		$controller->assign('baseLink', $this->doGet($request, 'findPost'));

		$this->findPost($controller, $request);
		return true;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function ajax_used($controller, $request) {
		$q = $request['q'];
		$data = $this->_ajax_used($q);
		echo json_encode($data);
	}

	function _ajax_used($q) {
		$db = newdb($this->dsn_r);
		$fmt = "SELECT id, code, name, emp FROM %s WHERE status = 1 AND code LIKE '%s'";
		$sql = sprintf($fmt, Constant::tbl_wl_used, $q . "%");
		// debug($sql);
		$result = $db->query($sql);
		$ret = array();
		while ($row = $db->fetch_array($result)) {
			$ret[] = $row;
		}

		return $ret;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function group($controller, $request) {
		$this->pretreat_group($controller);

		$num = array(
			'1' => '按次数',
			'2' => '按金额',
		);
		$controller->assign('num_option', $num);

		$controller->display($request, 'material/amount/group');
		return true;
	}

	function groupby($controller, $px) {
		$px = $this->groupby_aa($px, $this->groupby, 'emp');

		$controller->assign('groupby', $this->groupby[$px]);

		return $this->groupby_dd($px);
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function groupPost($controller, $request) {
		$this->pretreat($controller);
			
		$this->groupPara($controller, $request);

		$num_s = $request['num_s'];
		if (!empty($num_s) && $num_s == '2') {
			$fmt = "SELECT %s AS a, SUM(price*amount) AS c FROM %s a ";
		} else {
			$fmt = "SELECT %s AS a, COUNT(price) AS c FROM %s a ";
		}
		$sql = sprintf($fmt, $this->s, $this->tbl);

		$where = $this->_where($request);

		$request['sql'] = sprintf("%s %s GROUP BY %s ORDER BY %s %s", $sql, $where, $this->s, $this->orderby, $this->desc);

		$this->_group($controller, $request);

		// $controller->display($request, 'list');
		return true;
	}

	function _name($row, $px) {
		if (empty($px) || $px == '-' || $px == 'emp') {
			$row['a'] = sprintf("%s [%s]", Name::emp($row['a']), $row['a']);
		} elseif ($px == 'material') {
			$row['a'] = Name::material($row['a']);
		} else {

			$row = $this->_name_t($row, $px);
		}

		return $row;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function cal($controller, $request) {
		$this->pretreat($controller);

		$controller->assign('t1', strtotime('-1 month'));

		$controller->display($request, 'material/bom/cal');
		return true;
	}

	/**
	 *
	 *
	 * @param Controller $controller
	 * @param array $request
	 */
	function calPost($controller, $request) {
		$this->pretreat($controller);

		$emp = $this->_input($request['emp']);

		$date1 = $request['date1'];
		$date2 = $request['date2'];

		$content = addslashes($request['content']);

		$where = $this->_cal_where($emp, $date1, $date2);

		$db = newdb($this->dsn_w);
		$fmt = "UPDATE %s a, %s b SET a.category = b.category, a.subclass = b.subclass WHERE a.material = b.id %s";
		$sql = sprintf($fmt, $this->tbl, Constant::tbl_material, $where);
		debug($sql);
		$db->query($sql);

		$controller->assign('baseLink', $this->doGet($request, 'findPost'));

		$this->findPost($controller, $request);
		return true;
	}

	function _cal_where($emp, $date1, $date2) {
		$where = "";
		if (!empty($emp)) {
			$where .= " AND a.emp = '" . $emp . "'";
		}

		if (!empty($date1)) {
			$where .= " AND a.createtime >= '" . $date1 . "'";
		}

		if (!empty($date2)) {
			$where .= " AND a.createtime <= '" . $date2 . "'";
		}

		return $where;
	}
	
	function amount_zero($controller, $request) {
		$db = newdb($this->dsn_w);
		$fmt = "DELETE FROM %s WHERE amount = 0";
		$sql = sprintf($fmt, $this->tbl);
		echo $sql . "\n";
		$db->query($sql);
	}
	
	function z($controller, $request) {
		
		logdate($controller, $request);
		return true;
	}
		
	function _v1($s) {
		// $s = "230*120*50";
		$a = preg_split("/[\*|x]/i", $s);
		$r = floatval($a[0]) * floatval($a[1]) * floatval($a[2]) * pow(10, -9);

		return $r;
	}
	
	function _update($data, $amount, $place, $emp) {
		return $this->_in_update($data, $amount, $place, $emp);
	}
	
	function _update_returned($data, $amount, $place, $emp) {
		return $this->_in_update($data, -1 * $amount, $place, $emp);
	}
	
	function _in_update($data, $amount, $place, $emp) {
		$material = $data['material'];
		
		$name = addslashes($data['name']);
		$standard = addslashes($data['standard']);
		$unit = $data['unit'];
		$price = $data['price'];

		$db = newdb($this->dsn_w);
		$fmt = "SELECT * FROM %s WHERE place = '%s' AND name = '%s' AND standard = '%s' AND unit = '%s'";
		$sql = sprintf($fmt, $this->tbl, $place, $name, $standard, $unit);
		// $fmt = "SELECT * FROM %s WHERE name = '%s' AND standard = '%s' AND unit = '%s'";
		// $sql = sprintf($fmt, $this->tbl, $name, $standard, $unit);
		
		debug($sql);
		$result = $db->query($sql);
		if ($row = $db->fetch_array($result)) {
			$a = $row['price'] * floatval($row['amount']) + $data['price'] * $amount ;
			$b = floatval($row['amount']) + $amount;
		
			$price = $a / $b;
			
			$fmt = "UPDATE %s SET price = '%s', amount = '%s', modifytime = now() WHERE id = '%s'";
			$sql = sprintf($fmt, $this->tbl, $price, $b, $row['id']);
		} else {
			$fmt = "INSERT INTO %s(material, emp, name, standard, unit, price, amount, place, oper, createtime, modifytime)";
			$fmt .= " VALUES('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', now(), now())";
			$sql = sprintf($fmt, $this->tbl, $material, $emp, $name, $standard, $unit, $price, $amount, $place, $_SESSION['id']);
		}
		debug($sql);
		$db->query($sql);

		if ($db->affected_rows() > 0) {
			return true;
		}
		
		return false;	
	}
		
	function _out_update($id, $amount) {
		$db = newdb($this->dsn_w);
		$fmt = "UPDATE %s SET amount = amount - %s, modifytime = now() WHERE id = '%s'";
		$sql = sprintf($fmt, $this->tbl, $amount, $id);
		// debug($sql);
		$db->query($sql);
	}
	
	function _update_amount($id, $amount) {
		$db = newdb($this->dsn_w);
		$fmt = "UPDATE %s SET amount = '%s', modifytime = now() WHERE id = '%s'";
		$sql = sprintf($fmt, $this->tbl, $amount, $id);
		// debug($sql);
		$db->query($sql);
	}
	
	function _kc($name, $standard, $unit) {
		$db = newdb($this->dsn_r);
		$fmt = "SELECT place, amount FROM %s WHERE name = '%s' AND standard = '%s' AND unit = '%s'";
		$sql = sprintf($fmt, $this->tbl, $name, $standard, $unit);
		// debug($sql);
		$result = $db->query($sql);
		if ($row = $db->fetch_array($result)) {
			return $row;
		}

		return array();
	}
	
	function tj($controller, $request) {
		$bb = $this->_list_email('120');
		// print_r($bb);
		if (!$bb || count($bb) == 0) {
			return false;
		}
		
		$from = $this->email;
		$subject = '库存信息';
		
		$cc = array(
			'新增信息，金额大于100'=>array('w' => "price*amount > 100 AND DATE_FORMAT(createtime, '%Y-%m-%d') = DATE_FORMAT(DATE_ADD(now(), INTERVAL -1 DAY), '%Y-%m-%d')", 'b'=>'place'),
			'更新信息，金额大于100'=>array('w' => "price*amount > 100 AND DATE_FORMAT(modifytime, '%Y-%m-%d') = DATE_FORMAT(DATE_ADD(now(), INTERVAL -1 DAY), '%Y-%m-%d') AND DATE_FORMAT(createtime, '%Y-%m-%d') <> DATE_FORMAT(modifytime, '%Y-%m-%d')", 'b'=>'place'),			
		);
		
		if ($this->_tj_cc($controller, $cc)) {
			echo "222";
			return;
		}
		
		$controller->clear_assign('result');
		
		$body = $this->_tj_html($controller, $request, 'material/amount/tj_list');
		
		$this->_tj_mail($from, $bb, $subject, $body);

		logdate($controller, $request);
		return true;
	}

	function tjw($controller, $request) {
		$bb = $this->_list_email('120');
		// print_r($bb);
		if (!$bb || count($bb) == 0) {
			return false;
		}
		
		$from = $this->email;
		$subject = '库存信息（周报）';
		
		$cc = array(	
			'新增信息，金额大于500'=>array('w' => "price*amount > 500 AND DATE_FORMAT(createtime, '%Y-%V') = DATE_FORMAT(DATE_ADD(now(), INTERVAL -1 WEEK), '%Y-%V')", 'b'=>'place'),
			'更新信息，金额大于500'=>array('w' => "price*amount > 500 AND DATE_FORMAT(modifytime, '%Y-%V') = DATE_FORMAT(DATE_ADD(now(), INTERVAL -1 WEEK), '%Y-%V') AND DATE_FORMAT(createtime, '%Y-%m-%d') <> DATE_FORMAT(modifytime, '%Y-%m-%d')", 'b'=>'place'),			
		);
		
		$this->_tj_cc($controller, $cc);
		
		$aa = array(
			'一个星期之内'=>array('w' => "WHERE createtime >= DATE_FORMAT(DATE_ADD(now(), INTERVAL -7 DAY), '%Y-%m-%d')"),
			'一个月之内'=>array('w' => "WHERE createtime >= DATE_FORMAT(DATE_ADD(now(), INTERVAL -1 MONTH), '%Y-%m-%d')"),
			'三个月之内'=>array('w' => "WHERE createtime >= DATE_FORMAT(DATE_ADD(now(), INTERVAL -3 MONTH), '%Y-%m-%d')"),
			'半年之内'=>array('w' => "WHERE createtime >= DATE_FORMAT(DATE_ADD(now(), INTERVAL -6 MONTH), '%Y-%m-%d')"),
			'一年之内'=>array('w' => "WHERE createtime >= DATE_FORMAT(DATE_ADD(now(), INTERVAL -1 YEAR), '%Y-%m-%d')"),
			'全部'=>array('w' => "")
		);
		
		$this->_tj_bb($controller, $aa);

		$body = $this->_tj_html($controller, $request, 'material/amount/tj_list');
		
		$this->_tj_mail($from, $bb, $subject, $body);

		logdate($controller, $request);
		return true;
	}
	
	function _tj2($v) {
		$this->result_s = 10;
		$this->groupby_s = 'material';
			
		$s = $this->groupby_s;

		if (!empty($v['w'])) {
			$fmt = "SELECT %s AS a, SUM(price*amount) AS c FROM %s a %s GROUP BY %s ORDER BY c DESC";
			$sql = sprintf($fmt, $s, $this->tbl, $v['w'], $s);
		} else {
			$fmt = "SELECT %s AS a, SUM(price*amount) AS c FROM %s a GROUP BY %s ORDER BY c DESC";
			$sql = sprintf($fmt, $s, $this->tbl, $s);
		}		
		echo $sql . "\n";

		return $this->_group_tj2($sql);
	}
}
?>